﻿/*
 * tcpconnecteddevice.cpp
 *
 *  Created on: 2017年2月17日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_COM DM_API_EXPORT

#include <dm/os/com/tcpconnecteddevice.hpp>
#include <dm/os/log/logger.hpp>

namespace dm{
namespace os{
namespace com{

static const char* logModule = "CTcpConnectedDevice.com.os.dm";

CTcpConnectedDevice::CTcpConnectedDevice( ios_t& ios,const size_t& rxBufSize ):CDevice(rxBufSize),m_dev(ios){
	log().debug(THISMODULE "创建对象");
}

CTcpConnectedDevice::~CTcpConnectedDevice(){
	log().debug(THISMODULE "销毁对象");
	m_dev.shutdown(m_dev.shutdown_both);
	m_dev.close();
}

bool CTcpConnectedDevice::checkAndSetAddress( const CTcpConnectAddr& addr ){
	m_addr = addr;
	return true;
}

bool CTcpConnectedDevice::stopConnect(){
	m_dev.close();
	return true;
}

bool CTcpConnectedDevice::startSend( const dm::uint8* buf,const size_t& len ){
	try{
		boost::asio::async_write( m_dev,
				boost::asio::buffer(buf,len),
				boost::bind(&CTcpConnectedDevice::handler_tx,this,
						boost::asio::placeholders::error)
		);
	}catch( std::exception& e ){
		log().warnning(THISMODULE "send %d bytes fail(%s)",len,e.what());
		return false;
	}

	return true;
}

void CTcpConnectedDevice::start_rx(){
	try{
		m_dev.async_receive(boost::asio::buffer(m_rxBuf.get(),m_rxBufSize),
				boost::bind(&CTcpConnectedDevice::handler_rx,this,
						boost::asio::placeholders::error,
						boost::asio::placeholders::bytes_transferred )
				);
	}catch( std::exception& ec ){
		log().error(THISMODULE "开启监听失败%s",ec.what());
	}
}

void CTcpConnectedDevice::cancelDev(){
	try{
		m_dev.cancel();
	}catch( std::exception& ec ){
		log().error(THISMODULE "取消设备失败%s",ec.what());
	}
}

}
}
}


